<template>
    <div class="sheep-files-list">
        <!-- 查询条件区 -->
        <el-card class="search-card" shadow="never">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="可视耳号：">
                    <el-input v-model="searchForm.EarNumber" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label="电子耳号：">
                    <el-input v-model="searchForm.ELEarNumber" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label="品种：">
                    <el-select v-model="searchForm.Variety" placeholder="请选择" clearable style="width: 120px;">
                        <el-option v-for="item in breedOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="性别：">
                    <el-select v-model="searchForm.Sex" placeholder="请选择" clearable style="width: 80px;">
                        <el-option v-for="item in sexOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="月龄：">
                    <el-input v-model="searchForm.AgeByMonth" placeholder="请输入" style="width: 80px;" clearable />
                    <span style="margin: 0 4px;">-</span>
                    <el-input v-model="searchForm.AgeByDay" placeholder="请输入" style="width: 80px;" clearable />
                </el-form-item>
                <el-form-item label="生长阶段：">
                    <el-select v-model="searchForm.GrowthStage" placeholder="请选择" clearable style="width: 120px;">
                        <el-option v-for="item in growthStageOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="位置：">
                    <el-select v-model="searchForm.BuildingId" placeholder="栋舍" style="width: 120px;" clearable>
                        <el-option v-for="item in sheepfoldOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                    <el-select v-model="searchForm.Field" placeholder="栏位" style="width: 120px; margin-left: 4px;"
                        clearable>
                        <!-- 栏位选项可根据实际需求动态生成 -->
                    </el-select>
                </el-form-item>
                <el-form-item label="羊只类型：">
                    <el-select v-model="searchForm.SheepType" placeholder="请选择" clearable style="width: 100px;">
                        <el-option v-for="item in sheepTypeOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="出生日期：">
                    <el-date-picker v-model="searchForm.Birthday" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" />
                </el-form-item>
                <el-form-item label="生产等级：">
                    <el-select v-model="searchForm.ProductionGrade" placeholder="请选择" clearable style="width: 120px;">
                        <el-option v-for="item in productionLevelOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="销售等级：">
                    <el-select v-model="searchForm.SalesLevel" placeholder="请选择" clearable style="width: 120px;">
                        <el-option v-for="item in salesLevelOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="基因等级：">
                    <el-select v-model="searchForm.GeneticLevel" placeholder="请选择" clearable style="width: 120px;">
                        <el-option v-for="item in geneLevelOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="母耳号：">
                    <el-input v-model="searchForm.MotherEarNumber" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label="在场状态：">
                    <el-select v-model="searchForm.PresentStatus" placeholder="在场" clearable allow-create
                        style="width: 100px;">
                        <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="繁殖状态：">
                    <el-select v-model="searchForm.ReproductiveStatus" placeholder="请选择" clearable
                        style="width: 120px;">
                        <el-option v-for="item in reproductionStatusOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="繁殖状态天数：">
                    <el-input v-model="searchForm.PregnancyDays" placeholder="请输入" style="width: 80px;" clearable />
                </el-form-item>
                <el-form-item label="父耳号：">
                    <el-input v-model="searchForm.FatherEarNumber" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 操作按钮区 -->
        <div style="margin: 10px 0;">
            <el-button type="danger" @click="handleAddSheep">新增种公</el-button>
            <el-button type="danger" @click="handleAddMother">新增种母</el-button>
            <el-button type="danger" @click="handleAddLamb">新增后裔</el-button>
        </div>

        <!-- 主表格区（合并所有字段） -->
        <el-table :data="sheepList" border style="width: 100%;" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40" />
            <el-table-column fixed type="index" label="序号" width="50" />
            <el-table-column prop="EarNumber" label="可视耳号">
                <template #default="scope">
                    <el-link type="primary" @click="handleViewDetail(scope.row)" :underline="true"
                        style="font-weight: 500; cursor: pointer;">
                        {{ scope.row.EarNumber }}
                    </el-link>
                </template>
            </el-table-column>
            <el-table-column prop="ELEarNumber" label="电子耳号" />
            <el-table-column prop="Variety" label="品种" />
            <el-table-column prop="Sex" label="性别" />
            <el-table-column prop="Birthday" label="出生日期" width="120">
                <template v-slot="scope">
                    {{ moment(scope.row.Birthday).format('YYYY-MM-DD ') }}
                </template>
            </el-table-column>
            <el-table-column prop="AgeByDay" label="日龄" />
            <el-table-column prop="AgeByMonth" label="月龄" />
            <el-table-column prop="PresentStatus" label="在场状态" />
            <el-table-column prop="GrowthStage" label="阶段" />
            <el-table-column prop="SheepType" label="类型" />
            <el-table-column prop="House_name" label="栋舍" />
            <el-table-column prop="Field_Name" label="栏位" />
            <el-table-column prop="ReproductiveStatus" label="繁殖状态" />
            <el-table-column prop="PregnancyTest" label="是否妊检" />
            <el-table-column prop="ProductionGrade" label="生产等级" />
            <el-table-column prop="SalesLevel" label="销售等级" />
            <el-table-column prop="GeneticLevel" label="基因等级" />
            <el-table-column prop="BirthWeight" label="出生量" />
            <el-table-column prop="WeaningWeight" label="断奶量" />
            <el-table-column prop="WeaningDate" label="断奶日期" width="120">
                <template v-slot="scope">
                    {{ moment(scope.row.WeaningDate).format('YYYY-MM-DD') }}
                </template>
            </el-table-column>
            <el-table-column prop="FatherEarNumber" label="父耳号" />
            <el-table-column prop="MotherEarNumber" label="母耳号" />

        </el-table>

        <!-- 分页器 -->
        <div class="pagination-section">
            <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
                :page-sizes="[5, 10, 20, 30, 50, 100]" :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" :background="true" :small="false" class="pagination-component" />

            <!-- 分页信息显示 -->
            <div class="pagination-info" v-if="pagination.total > 0">
                <span>
                    显示第 {{ (pagination.page - 1) * pagination.pageSize + 1 }} 到
                    {{ Math.min(pagination.page * pagination.pageSize, pagination.total) }} 条记录，
                    共 {{ pagination.total }} 条记录，
                    共 {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
                </span>
            </div>
        </div>

    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Sheep_BreedingRead } from '@/utils/Interceptors'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import moment from 'moment'

const router = useRouter()

// 下拉选项数据
const breedOptions = [
    '杜泊', '澳洲白', '萨福克', '杜湖', '杜杜湖', '萨杜湖', '澳湖', '湖羊', '澳杜湖'
]
const sexOptions = ['母', '公']
const growthStageOptions = ['乳羊', '保育', '后备公羊', '后备母羊', '后备羊']
const sheepfoldOptions = ['大羊舍', '配种舍', '采购羊舍']
const sheepTypeOptions = ['种公', '种母', '后备']
const geneLevelOptions = ['后备级', '核心级', '生产级', '未定级']
const productionLevelOptions = ['后备群', '生产群', '核心群', '未定级']
const salesLevelOptions = ['无', '未定级']
const reproductionStatusOptions = [
    '后备空怀', '返情空怀', '未孕空怀', '流产空怀', '空胎空怀', '断奶空怀', '妊娠', '哺乳'
]
const statusOptions = [
    '在场', '待入场', '销售离场', '死亡离场', '淘汰已入场', '调拨离场', '死羔未入场'
]

// 查询表单数据

const searchForm = ref({
    EarNumber: '',
    ELEarNumber: '',
    Variety: '',
    Sex: '',
    Birthday: '',
    AgeByDay: '',
    AgeByMonth: '',
    GrowthStage: '',
    BuildingId: '',
    Field: '',
    SheepType: '',
    ReproductiveStatus: '',
    PregnancyDays: '',
    ProductionGrade: '',
    motherEarId: '',
    GeneticLevel: '',
    FatherEarNumber: '',
    MotherEarNumber: '',
    PresentStatus: '',
})

const sheepList = ref([])
const pagination = ref({
    page: 1,
    pageSize: 5,
    total: 0
})

function mapFormToDto() {
    // 映射前端表单到后端DTO
    return {
        EarNumber: searchForm.value.EarNumber,
        ELEarNumber: searchForm.value.ELEarNumber,
        Variety: searchForm.value.Variety,
        Sex: searchForm.value.Sex,
        Birthday: searchForm.value.Birthday,
        AgeByDay: searchForm.value.AgeByDay,
        AgeByMonth: searchForm.value.AgeByMonth,
        GrowthStage: searchForm.value.GrowthStage,
        BuildingId: searchForm.value.BuildingId,
        Field: searchForm.value.Field,
        SheepType: searchForm.value.SheepType,
        ReproductiveStatus: searchForm.value.ReproductiveStatus,
        PregnancyDays: searchForm.value.PregnancyDays,
        ProductionGrade: searchForm.value.ProductionGrade,
        SalesLevel: searchForm.value.SalesLevel,
        GeneticLevel: searchForm.value.GeneticLevel,
        FatherEarNumber: searchForm.value.FatherEarNumber,
        MotherEarNumber: searchForm.value.MotherEarNumber,
        PageIndex: pagination.value.page,
        PageSize: pagination.value.pageSize
    }
}

onMounted(() => {
    handleSearch()
})
//
async function handleSearch() {
    const params = mapFormToDto()
    console.log('搜索参数:', params) // 调试用

    try {
        const res = await Sheep_BreedingRead.get('/api/SheepFiles/GetList', { params })
        console.log('API返回数据:', res.data) // 调试用
        console.log('API返回数据:', res.data.data.PageData) // 调试用
        if (res.data.code === 200) {
            sheepList.value = res.data.data.PageData || []
            pagination.value.total = res.data.data.TotalCount || 0

            console.log('设置数据:', {
                dataCount: sheepList.value.length,
                total: pagination.value.total,
                currentPage: pagination.value.page,
                pageSize: pagination.value.pageSize
            })
        } else {
            sheepList.value = []
            pagination.value.total = 0
            ElMessage.error(res.data.msg || '查询失败')
        }
    } catch (e) {
        console.error('查询异常:', e)
        sheepList.value = []
        pagination.value.total = 0
        ElMessage.error('查询失败，请稍后重试')
    }
}

function handleSizeChange(val) {
    console.log('每页条数变化:', val)
    pagination.value.pageSize = val
    pagination.value.page = 1 // 重置到第一页
    handleSearch()
}

function handleCurrentChange(val) {
    console.log('当前页变化:', val)
    pagination.value.page = val
    handleSearch()
}

function handleReset() {
    Object.keys(searchForm.value).forEach(key => {
        if (Array.isArray(searchForm.value[key])) {
            searchForm.value[key] = []
        } else {
            searchForm.value[key] = ''
        }
    })
    pagination.value.page = 1
    pagination.value.pageSize = 5 // 重置为默认页面大小
    handleSearch()
}

function handleAddSheep() {
    // 新增种羊逻辑
    router.push('/SheepFilesAdd1')
}
function handleAddMother() {
    // 新增种母逻辑
    router.push('/SheepFilesAdd2')
}
function handleAddLamb() {
    // 新增羔羊逻辑
    router.push('/SheepFilesAdd3')
}

function handleSelectionChange(val) {
    // 多选逻辑
}




// 查看羊只详情（当前页面跳转）
function handleViewDetail(row) {
    console.log('点击的行数据:', row) // 调试用

    // 尝试多种可能的ID字段名
    const sheepId = row.Id || row.SheepFilesId || row.sheepFilesId || row.id
    console.log('获取到的羊只ID:', sheepId) // 调试用

    if (!sheepId) {
        ElMessage.error('无法获取羊只档案ID')
        console.error('行数据中没有找到有效的ID字段:', Object.keys(row))
        return
    }

    // 直接在当前页面跳转到详情页
    router.push({
        name: 'SheepFilesDetail',
        query: {
            id: sheepId,
            earNumber: row.EarNumber,
            elEarNumber: row.ELEarNumber
        }
    })
}

// 添加快速跳转功能
const quickJumpPage = ref('')

// 快速跳转到指定页
function quickJump() {
    const targetPage = parseInt(quickJumpPage.value)
    const maxPage = Math.ceil(pagination.value.total / pagination.value.pageSize)

    if (isNaN(targetPage) || targetPage < 1 || targetPage > maxPage) {
        ElMessage.warning(`请输入1-${maxPage}之间的页码`)
        quickJumpPage.value = ''
        return
    }

    pagination.value.page = targetPage
    quickJumpPage.value = ''
    handleSearch()
}

// 跳转到第一页
function goToFirstPage() {
    if (pagination.value.page !== 1) {
        pagination.value.page = 1
        handleSearch()
    }
}

// 跳转到最后一页
function goToLastPage() {
    const maxPage = Math.ceil(pagination.value.total / pagination.value.pageSize)
    if (pagination.value.page !== maxPage) {
        pagination.value.page = maxPage
        handleSearch()
    }
}
</script>

<style scoped>
.sheep-files-list {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
}

.search-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-card .el-card__body {
    padding: 20px;
}

/* 表格容器样式 */
.table-container {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

/* 表格头部样式 */
.el-table th.el-table__cell {
    background-color: #fafafa;
    color: #606266;
    font-weight: 500;
    border-bottom: 1px solid #ebeef5;
}

/* 表格行样式 */
.el-table .el-table__row:hover>td {
    background-color: #f5f7fa;
}

/* 分页信息显示 */
.pagination-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
    padding: 0 20px;
    color: #909399;
    font-size: 12px;
}

.pagination-section {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    padding: 20px 0;
}

.pagination-component {
    --el-pagination-font-size: 14px;
    --el-pagination-bg-color: #fff;
    --el-pagination-text-color: #606266;
    --el-pagination-border-radius: 4px;
    --el-pagination-button-color: #606266;
    --el-pagination-button-bg-color: #fff;
    --el-pagination-button-disabled-color: #c0c4cc;
    --el-pagination-button-disabled-bg-color: #fff;
    --el-pagination-hover-color: #409eff;
}

.pagination-component .el-pagination__total {
    margin-right: 10px;
    font-weight: 400;
    color: #909399;
}

.pagination-component .el-pagination__sizes {
    margin-right: 10px;
}

.pagination-component .el-pagination__jump {
    margin-left: 10px;
}
</style>
